package thread.ReadWriteThread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteThread implements Runnable {

    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
    static ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();



    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0;i<100;i++){
            Thread thread = new Thread(new ReadWriteThread(true), "读线程" + i);
            executorService.execute(thread);
            if (i == 7 || i == 10 || i ==66){
                Thread thread1 = new Thread(new ReadWriteThread(false), "写线程" + i);
                executorService.execute(thread1);

            }
        }
    }
    static int a = 0;
    boolean flag = true;

    public ReadWriteThread(boolean flag) {
        this.flag = flag;
    }

    @Override
    public void run() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //读
            if (flag) {
                readLock.lock();
                System.out.println(Thread.currentThread().getName() + "读数据:" + a);
                readLock.unlock();
            } else {
                //写
                writeLock.lock();
                a++;
                System.out.println(Thread.currentThread().getName() + "写数据:" + a);
                writeLock.unlock();
            }


    }
}
